/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.system.uploadfile.action;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import me.ijleex.mgmt.framework.entity.Result;
import me.ijleex.mgmt.framework.page.Page;
import me.ijleex.mgmt.framework.spring.ControllerSupport;
import me.ijleex.mgmt.system.uploadfile.entity.UploadFile;
import me.ijleex.mgmt.system.uploadfile.service.IUploadFileService;

/**
 * 上传文件 Action
 *
 * @author liym
 * @since 2019-12-06 14:58 新建
 */
@RequestMapping("/system/upload-file")
@Controller
public class UploadFileAction extends ControllerSupport<UploadFile> {

    private final IUploadFileService service;

    public UploadFileAction(IUploadFileService service) {
        this.service = service;
    }

    /**
     * 上传文件
     *
     * @param request 请求
     * @param file 上传文件
     * @param encrypt 是否加密
     * @return 上传结果
     * @since 2019-12-07 22:12
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result uploadFile(HttpServletRequest request, MultipartFile file, String encrypt) {
        try {
            byte[] fileBytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String contentType = file.getContentType();
            long fileSize = file.getSize();

            // TODO 获取当前用户 ID
            long userId = 577054734542819328L;

            return this.service.uploadFile(fileBytes, originalFilename, contentType, fileSize, Long.toString(userId), Boolean.parseBoolean(encrypt));
        } catch (IOException e) {
            return Result.error("上传文件失败");
        }
    }

    /**
     * 查询 上传文件列表
     *
     * <p>http://localhost:8082/ij-mgmt/system/upload-file/list?pageNo=1&pageSize=7</p>
     */
    @GetMapping("/list")
    @ResponseBody
    public Page<UploadFile> getFileList(HttpServletRequest request, UploadFile obj) {
        this.setPageParams(request, obj);
        List<UploadFile> list = this.service.getFileList(obj);
        return this.wrapPageData(list, obj);
    }

    /**
     * 获取文件
     *
     * @param path 文件路径
     * @return 结果
     */
    @GetMapping("/get")
    @ResponseBody
    public Result getFileByPath(String path) {
        return this.service.getFileByPath(path);
    }

}
